package com.android.lovingpet.community.search;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.android.lovingpet.base.BasePresenter;
import com.android.lovingpet.common.Back;

import java.util.ArrayList;

public class SearchPresenter extends BasePresenter<ISearchContract.View> implements ISearchContract.Presenter {

    private ISearchContract.View view;

    public SearchPresenter(ISearchContract.View view) {
        this.view = view;
    }

    @Override
    public void search(String query) {
        view.clearData();
        final ArrayList<Integer> modes = new ArrayList<>();
        modes.add(1);
        modes.add(2);
        modes.add(3);
        for (int i = 0; i < query.length(); i++) {
            char ch = query.charAt(i);
            if (!Character.isDigit(ch)) {
                modes.remove(Integer.valueOf(1));
                break;
            }
        }
        if (!query.contains("@")) {
            modes.remove(Integer.valueOf(2));
        }

        for (int i : modes) {
            SearchModel.getInstance().search(query, i, new Back() {
                @Override
                public void onFailure(String meg) {
                    view.showToast(meg);
                }

                @Override
                public void onSuccess(@Nullable Bundle bundle) {
                    ArrayList accounts = null;
                    if (bundle.getParcelableArrayList("accounts") != null) {
                        accounts = new ArrayList<>(bundle.getParcelableArrayList("accounts"));
                    }
                    view.setData(accounts);
                }
            });
        }
    }

}
